package model

import (
	"app/internal/structs/requests"
	"app/pkg/db"
	"errors"
	"strings"

	"gorm.io/gorm"
)

type SettingModel struct {
	CommonStruct
	Name string `json:"name" gorm:"column:name"`
	Data string `json:"data" gorm:"column:data"`
}

const (
	IndexShufflingImg = "index_shuffling_img" //首页轮播图
)

func NewSettingModel() *SettingModel { return &SettingModel{} }

func (m *SettingModel) TableName() string { return "setting" }

func (m *SettingModel) GetInfoByName(name string) (s SettingModel, err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Model(&m).Where("name=?", name).Take(&s).Error
	return
}

func (m *SettingModel) GetInfoByNameBatch(name []string) (s []SettingModel, err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	err = conn.Model(&m).Where("name in (?)", name).Find(&s).Error
	return
}

func (m *SettingModel) Set(name, data string) (err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	data = strings.Trim(data, " ")
	old, err := m.GetInfoByName(name)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		//新增
		old.Data = data
		old.Name = name
		return conn.Model(&m).Omit("created_at", "updated_at").Create(&old).Error
	} else if err != nil {
		return
	} else {
		old.Data = data
		return conn.Model(&m).Where("name = ?", name).Updates(old).Error

	}
}

func (m *SettingModel) SetBatch(d []requests.SettingSet) (err error) {
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	for _, val := range d {
		data := strings.Trim(val.Data, " ")
		old, err := m.GetInfoByName(val.Name)
		if errors.Is(err, gorm.ErrRecordNotFound) {
			//新增
			old.Data = val.Data
			old.Name = val.Name
			err = conn.Model(&m).Omit("create_time", "update_time").Create(&old).Error
		} else if err != nil {
			continue
		} else {
			old.Data = data
			err = conn.Model(&m).Where("name = ?", val.Name).Updates(old).Error
		}
	}
	return
}
